package com.daniel.dianping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daniel.dianping.dto.LoginFormDTO;
import com.daniel.dianping.dto.Result;
import com.daniel.dianping.dto.UserDTO;
import com.daniel.dianping.entity.User;
import com.daniel.dianping.mapper.UserMapper;
import com.daniel.dianping.service.IUserService;
import com.daniel.dianping.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.daniel.dianping.utils.RedisConstants.*;
import static com.daniel.dianping.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * 服务实现类
 *
 * @author 10192
 * @return com.daniel.dianping.service.impl
 * @date 2022/7/8 22:31
 * @versions 1.0.0
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.验证手机号是否合法
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号码不合法");
        }
        // 2.生产验证码
        String code = RandomUtil.randomNumbers(6);
        // 3.保存验证码保存到Redis过期时间2min
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, CACHE_TTL_2, TimeUnit.MINUTES);
        // 4.模拟发送验证码
        log.debug("发送验证码成功，验证码为：{}", code);
        // 5.返回
        return Result.ok();
    }
    
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号不合法");
        }
        // 获取在Redis保存的验证码进行校验
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (code == null || !loginForm.getCode().equals(code)) {
            return Result.fail("验证码错误!!");
        }
        // 查询用户数据
        User user = query().eq("phone", phone).one();
        if (user == null) {
            user = createUser(phone);
        }
        // 7.2.将User对象转为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 将用户数据保存到Redis过期时间30min
        String uuid = UUID.randomUUID(false).toString();
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldVal) -> fieldVal.toString()));
        // 保存redis的token
        String token = LOGIN_USER_KEY + uuid;
        stringRedisTemplate.opsForHash().putAll(token, userMap);
        stringRedisTemplate.expire(token, CACHE_TTL_30, TimeUnit.MINUTES);
        
        // 返回token 并让前端携带token
        return Result.ok(uuid);
    }
    
    /**
     * 创建一个新用户
     *
     * @param phone
     * @return
     */
    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
